package com.witmore.skyline.web.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Description: ThreadPoolConfig
 * Author: 豆子高
 * Date: 2025/3/15 15:05
 */
@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        return new ThreadPoolExecutor(
                10,
                10,
                60L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

    /**
     * 设备同步专用线程池 - 设备级并发控制
     * 适配2核2G服务器配置
     */
    @Bean("deviceSyncExecutor")
    public ThreadPoolExecutor deviceSyncExecutor() {
        return new ThreadPoolExecutor(
                4,     // 核心线程数: 2核CPU × 2
                6,     // 最大线程数: 适度超配
                60L,   // 空闲时间: 60秒
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(50),  // 队列容量: 缓存2-3页数据
                new ThreadPoolExecutor.CallerRunsPolicy()  // 拒绝策略: 调用者执行
        );
    }

    /**
     * API调用专用线程池 - API级并发控制
     * 用于执行具体的第三方API调用
     */
    @Bean("apiCallExecutor") 
    public ThreadPoolExecutor apiCallExecutor() {
        return new ThreadPoolExecutor(
                6,     // 核心线程数: 4设备 × 1.5倍
                10,    // 最大线程数: 高峰期扩展
                60L,   // 空闲时间: 60秒
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(20),  // 队列容量: 控制内存
                new ThreadPoolExecutor.CallerRunsPolicy()  // 拒绝策略
        );
    }

}
